<?php



use Workerman\Worker;
require_once'./Workerman/Autoloader.php';

$worker = new Worker('websocket://0.0.0.0:2345');
$global_uid = 0;
$username="";

$worker->onConnect = function($connection)	//当用户连接上
{	

	global $global_uid;
		
	global $worker;

	$connection->uid =++$global_uid;


	$worker->onMessage=function($connection,$data){

		global $worker;

		$data=json_decode($data,true);	//接收发送来的数据

		if($data['once']=='once'){	//判断是否为第一次连接

			$arr=[
				"user"=>$data['user'],
				"once"=>$data['once']
			];

			$firstConnSendData=json_encode($arr);


			global $username;	//全局使用这个username
			
			$username=$connection->user=$arr['user'];	//用户的名字为他第一次传进来的名字

			foreach($worker->connections as $conn)	//广播发送用户XXX进入了聊天室
			{
			    $conn->send($firstConnSendData);
			}	
		}else{	//else以下的逻辑处理聊天信息

			$arr=[
				"text"=>$data['text'],
				"status"=>"usersend"
			];

			$sendData=json_encode($arr);

			foreach($worker->connections as $key =>$conn)	
			{
			    if($key!=$connection->id){	//除去发送进来的那位用户,广播发送
			    	$conn->send($sendData);	
			    }
			    

			}	

		}
       

	};
		
};


$worker->onClose=function($connection){
	global $worker;
	global $username;
	$arr=[
		"user"=>$username,
		"status"=>"logout"
	];

	$str=json_encode($arr);

	  foreach($worker->connections as $conn)
    {
        $conn->send($str);
    }


};

	
// 运行worker
Worker::runAll();
